package com.mpd.core;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;

import java.util.Enumeration;
import java.util.Map;

import com.google.common.collect.Maps;

/**
 * 
 * @className:SerialPortAdapter.java
 * @classDescription:串口适配器
 * @author: DANIEL DENG
 * @createTime: 2014-1-2
 *
 */
public class SerialPortAdapter {
	
	/**
	 * 串口缓存-Map对象
	 */
	private Map<String,CommPortIdentifier> serialPortCache = Maps.newConcurrentMap();
	
	/**
	 * 未被占用的串口缓存
	 */
	private Map<String,CommPortIdentifier> availableSerialPortCache = Maps.newConcurrentMap();

	/**
	 * 获取串口缓存
	 * @return
	 */
	public Map<String, CommPortIdentifier> getSerialPortCache() {
		return serialPortCache;
	} 
	
	/**
	 * 刷新串口缓存
	 */
	@SuppressWarnings({ "rawtypes", "unused" })
	private void refreshSerialPortCache(){
	     Enumeration piEnumeration = CommPortIdentifier.getPortIdentifiers();  
	     CommPortIdentifier cpid;  
        while(piEnumeration.hasMoreElements()){  
            cpid = (CommPortIdentifier)piEnumeration.nextElement();  
            if( cpid.getPortType() == CommPortIdentifier.PORT_SERIAL ){  
            	serialPortCache.put(cpid.getName(), cpid);
            	if( !cpid.isCurrentlyOwned() ){
            		//未被占用
            		availableSerialPortCache.put(cpid.getName(), cpid);
            	}
            }
        }  
	}
	
	/**
	 * 打开串口端口
	 * @param appName
	 * @param portName
	 * @param timeout
	 * @return
	 */
	public SerialPort openPort(String appName ,String portName ,int timeout ){
		SerialPort serialPort ;
		if( !availableSerialPortCache.isEmpty() ){
			CommPortIdentifier  commPort = availableSerialPortCache.get(portName);
	            try{  
	            	serialPort = (SerialPort)commPort.open(appName, timeout);  
	            	availableSerialPortCache.remove(portName);
	            	return  serialPort ;
	            }catch(PortInUseException e){  
	                throw new RuntimeException(String.format("端口'%1$s'正在使用中！",   
	                        commPort.getName()));  
	            }  
		}else{
			//不需要实现
		}
		
		//不能正常打开端口
		return null;
	}
	

}
